/* $RCSFile: EnhancedLinks.ascx.cs $
 * Apache license v2 2011 by Christian Surieux
 * $Source: ?/AddonNice/PageModules/EnhancedLinks/EnhancedLinks.ascx.cs $
 * $log$
 * Revision 20 2010/08/09 10:51:20  christian.surieux
 *   Added Log comment to all .aspx .ascx .master files
 * Revision 19 2010/08/09 09:43:53  christian.surieux
 *   Added Log to cs sources files
 * Revision 6 2010/08/06 19:56:25  christian.surieux
 *   Added Log to All cs files
 */

using System;
using System.Globalization;
using System.Diagnostics;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Text;
using System.Drawing;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;

using AddonNice.UI;
using AddonNice.UI.WebControls;
using AddonNice.UI.DataTypes;
using AddonNice.Configuration;
using AddonNice.Configuration.Settings;
using AddonNice.Settings;
using AddonNice.Diagnostics;
using AddonNice.Helpers;
using AddonNice.Settings.PageModules.EnhancedLink;
using AddonNice.Core;

using Trace2 =  System.Diagnostics.Trace;

namespace AddonNice.PageModules.EnhancedLinks
{
    public class EStr
    {
        #region settings
	    public const string ENHANCEDLINKS_ICONPATH          =   "ENHANCEDLINKS_ICONPATH";
		public const string ENHANCEDLINKS_MAXCOLUMS         =   "ENHANCEDLINKS_MAXCOLUMS";
		public const string ENHANCEDLINKS_SWITCHERTYPES     =   "ENHANCEDLINKS_SWITCHERTYPES";
		public const string ENHANCEDLINKS_DEFAULTIMAGE      =   "ENHANCEDLINKS_DEFAULTIMAGE";
		public const string ENHANCEDLINKS_EXPANDALL         =   "ENHANCEDLINKS_EXPANDALL";
		public const string ENHANCEDLINKS_DRAWHR            =   "ENHANCEDLINKS_DRAWHR";
		public const string ENHANCEDLINKS_PERCENT_RESIZE_IMG=   "ENHANCEDLINKS_PERCENT_RESIZE_IMG";
		public const string ENHANCEDLINKS_CELLPADDING       =   "ENHANCEDLINKS_CELLPADDING";
		public const string ENHANCEDLINKS_CELLSPACING       =   "ENHANCEDLINKS_CELLSPACING";
        
    #endregion settings
    
        #region resource strings
        public const string ENHANCEDLINKS_EDITLINK          =   "ENHANCEDLINKS_EDITLINK";
        public const string ENHANCEDLINKS_DROPDOWNLIST      =   "ENHANCEDLINKS_DROPDOWNLIST";
        public const string ENHANCEDLINKS_LINKS             =   "ENHANCEDLINKS_LINKS";
    #endregion resource strings
    }

    /// <summary>
    /// Initializer class for EnhancedLinks 
    /// </summary>
    public class EnhancedLinksSI : PortalModuleControlSI
    {
        public EnhancedLinksSI(ModuleSettingsDictionary bSettings,ISettingsOwner pm) : base()
        {
            if ( ModuleTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]EnhancedLinksSI Ctor BEG.",ModuleTraceSwitch.Sw.Info);
            InitSettings(bSettings,pm);
            if ( ModuleTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]EnhancedLinksSI Ctor END.",ModuleTraceSwitch.Sw.Info);
        }
 
        public override void InitSettings(ModuleSettingsDictionary bSettings,ISettingsOwner pm)
        {             
            if ( ModuleTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]EnhancedLinksSI InitSettings BEG.",ModuleTraceSwitch.Sw.Info);
            
            base.InitSettings(bSettings,pm);

		    string extgrp                   =   pm.ExtendedResourcesGroup;
			SettingItemSpecial IconPath     =   null;
			if (portalSettings != null)
			{
				IconPath                    =   new SettingItemSpecial(EStr.ENHANCEDLINKS_ICONPATH,
                    new FolderDataType(HttpContext.Current.Server.MapPath(portalSettings.PortalFullPath ), "IconContainer"));
				IconPath.Value              =   "IconContainer";
				IconPath.Order              =   5;
				IconPath.ExtendedGroupName  =   extgrp;
			    IconPath.EnglishName        =   "Container for Icons";
				IconPath.Description        =   "Portal directory for upload used icons";
			    bSettings.AddSetting(IconPath);
			}
            
            ArrayList styleLink             =   new ArrayList();
			styleLink.Add(new SettingOption(1, LocalizeHelper.Localize(EStr.ENHANCEDLINKS_DROPDOWNLIST, "DropDownList")));
            styleLink.Add(new SettingOption(2, LocalizeHelper.Localize(EStr.ENHANCEDLINKS_LINKS, "Links")));

			SettingItemSpecial MaxColums    =   new SettingItemSpecial(EStr.ENHANCEDLINKS_MAXCOLUMS,new IntegerDataType());
			MaxColums.Value                 =   "1";
			MaxColums.MinValue              =   1;
			MaxColums.MaxValue              =   100;
			MaxColums.EnglishName           =   "Max Colums";
			MaxColums.Description           =   "Maximun number of colums";
			MaxColums.ExtendedGroupName     =   extgrp;
			MaxColums.Order                 =   10;
			bSettings.AddSetting(MaxColums);

			SettingItemSpecial labelStyleLink = new SettingItemSpecial(EStr.ENHANCEDLINKS_SWITCHERTYPES,
                new CustomListDataType(styleLink, "Name", "Val"));
			labelStyleLink.Description      =   "Select here how your module should look like";
			labelStyleLink.EnglishName      =   "Style Links";
			labelStyleLink.Value            =   "2";
			labelStyleLink.ExtendedGroupName  =   extgrp;
			labelStyleLink.Order            =   15;
			bSettings.AddSetting(labelStyleLink);

			SettingItemSpecial ImageDefault =   new SettingItemSpecial(EStr.ENHANCEDLINKS_DEFAULTIMAGE,new StringDataType());
			ImageDefault.Value              =   "navLink.gif";
			ImageDefault.EnglishName        =   "Default Image for link";
			ImageDefault.Description        =   "Select here a image for links with no special setting image";
			ImageDefault.ExtendedGroupName  =   extgrp;
			ImageDefault.Order              =   20;
			bSettings.AddSetting(ImageDefault);

			SettingItemSpecial ExpandAll    =   new SettingItemSpecial(EStr.ENHANCEDLINKS_EXPANDALL,new BooleanDataType());
			ExpandAll.Value                 =   StStr.strFalse;
			ExpandAll.EnglishName           =   "Show Description";
			ExpandAll.Description           =   "Mark this if you like to see the description down the link";
			ExpandAll.ExtendedGroupName     =   extgrp;
			ExpandAll.Order                 =   25;
			bSettings.AddSetting(ExpandAll);

            SettingItemSpecial DrawHr       =   new SettingItemSpecial(EStr.ENHANCEDLINKS_DRAWHR,new BooleanDataType());
			DrawHr.Value                    =   StStr.strTrue;
			DrawHr.EnglishName              =   "Draw line after group";
			DrawHr.Description              =   "Check to draw a line after any Group item";
			DrawHr.ExtendedGroupName        =   extgrp;
			DrawHr.Order                    =   30;
			bSettings.AddSetting(DrawHr);

			SettingItemSpecial ImgResize    =   new SettingItemSpecial(EStr.ENHANCEDLINKS_PERCENT_RESIZE_IMG,new IntegerDataType());
			ImgResize.Value                 =   "0";
			ImgResize.EnglishName           =   "Image resize %";
			ImgResize.Description           =   "Percentage for image resize, zero for no resize";
			ImgResize.ExtendedGroupName     =   extgrp;
			ImgResize.Order                 =   35;
			bSettings.AddSetting(ImgResize);

        
			SettingItemSpecial CellPadding  =   new SettingItemSpecial(EStr.ENHANCEDLINKS_CELLPADDING,new IntegerDataType());
			CellPadding.Value               =   "0";
			CellPadding.EnglishName         =   "Cell padding";
			CellPadding.Description         =   "General table cell padding";
			CellPadding.ExtendedGroupName   =   extgrp;
			CellPadding.Order               =   40;
			bSettings.AddSetting(CellPadding);

			SettingItemSpecial CellSpacing  =   new SettingItemSpecial(EStr.ENHANCEDLINKS_CELLSPACING,new IntegerDataType());
			CellSpacing.Value               =   "0";
			CellSpacing.EnglishName         =   "Cell spacing";
			CellSpacing.Description         =   "General table cell spacing";
			CellSpacing.ExtendedGroupName   =   extgrp;
			CellSpacing.Order               =   45;
			bSettings.AddSetting(CellSpacing);
            if ( ModuleTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]EnhancedLinksSI InitSettings END.",ModuleTraceSwitch.Sw.Info);
        }
    }

    public partial class EnhancedLinks : PortalModuleControl 
	{
    	EnhancedLinkDB eDB      =   new EnhancedLinkDB();
        // utilities formats
        const string fmt2       =   "<td>&nbsp;</td>";
        const string fmt2b      =   "<td></td>";
        const string fmt3       =   "</td>";
        const string fmt4       =   "</tr>\r\n<tr>";
        
        // Table
        const string fmttbl     =   "<table border='0' cellspacing='{0}' cellpadding='{1}' class='EnhancedLinkTable EnhancedLinkTable_{2}' >";

        // Edit image in edit mode
        const string fmta       =   "<td class='EnhancedLinkCellEdit'><a href=\"{0}\"><asp:Image skinID='Item_Edit' runat='server' BorderWidth='0' /></a></td>";
        const string xfmta      =   "<td class='EnhancedLinkCellEdit'></td>";
        
        // normal item: Image before title
	    const string fmtb0      =   "<td><img src='{0}' border='0' alt='{1}' style='width: {2}%;' /></td>";
	    const string fmtb0md2   =   "<td colspan='2'><a class='EnhancedLink EnhancedLink_{3}' href='{4}' target='{5}' title='{6}'><img src='{0}' border='0' alt='{1}' style='width: {2}%;' /></a></td>";
        
        const string fmtb       =   "<td class='EnhancedLinkCellImg EnhancedLinkCellImg_{3}'><img src='{0}' border='0' alt='{1}' style='width: {2}%;' /></td>";
        const string fmtbmd2    =   "<td class='EnhancedLinkCellImg EnhancedLinkCellImg_{3}' colspan='2'><a class='EnhancedLink EnhancedLink_{3}' href='{4}' target='{5}' title='{6}'><img src='{0}' border='0' alt='{1}' style='width: {2}%;' /></a></td>";

        const string fmtb2      =   "<td class='EnhancedLinkCellImg EnhancedLinkCellImg_{2}'><img src='{0}' border='0' alt='{1}' /></td>";
        const string fmtb2md2   =   "<td class='EnhancedLinkCellImg EnhancedLinkCellImg_{2}' colspan='2'><a class='EnhancedLink EnhancedLink_{2}' href='{3}' target='{4}' title='{5}'><img src='{0}' border='0' alt='{1}' /></a></td>";
        const string fmtb20     =   "<td><img src='{0}' border='0' alt='{1}' /></td>";
        const string fmtb20md2  =   "<td colspan='2'><a class='EnhancedLink EnhancedLink_{2}' href='{3}' target='{4}' title='{5}'><img src='{0}' border='0' alt='{1}' /></a></td>";
    	
        const string fmtbe0     =   "<td><img src='{0}' border='0' alt='{1}' style='width: {2}%;' /></td>";
        const string fmtbe0md2  =   "<td colspan='2'><a class='EnhancedLink EnhancedLink_{3}' href='{4}' target='{5}' title='{6}'><img src='{0}' border='0' alt='{1}' style='width: {2}%;' /></a></td>";

        const string fmtbe      =   "<td class='EnhancedLinkCellImgEdit EnhancedLinkCellImg_{3}'><img src='{0}' border='0' alt='{1}' style='width: {2}%;' /></td>";
	    const string fmtbemd2   =   "<td class='EnhancedLinkCellImgEdit EnhancedLinkCellImg_{3}' colspan='2'><a class='EnhancedLink EnhancedLink_{3}' href='{4}' target='{5}' title='{6}'><img src='{0}' border='0' alt='{1}' style='width: {2}%;' /></a></td>";
	    
        const string fmtb2e     =   "<td class='EnhancedLinkCellImgEdit EnhancedLinkCellImg_{2}'><img src='{0}' border='0' alt='{1}' /></td>";
        const string fmtb2emd2  =   "<td class='EnhancedLinkCellImgEdit EnhancedLinkCellImg_{2}' colspan='2'><a class='EnhancedLink EnhancedLink_{2}' href='{3}' target='{4}' title='{5}'><img src='{0}' border='0' alt='{1}' /></a></td>";
	    
        const string fmtb2e0    =   "<td><img src='{0}' border='0' alt='{1}' /></td>";
        const string fmtb2e0md2 =   "<td colspan='2'><a class='EnhancedLink EnhancedLink_{2}' href='{3}' target='{4}' title='{5}'><img src='{0}' border='0' alt='{1}' /></a></td>";

	    const string xfmtb0     =   "<td></td>";
	    const string xfmtb      =   "<td class='EnhancedLinkCellImg EnhancedLinkCellImg_{0}'></td>";
	    const string xfmtbe     =   "<td class='EnhancedLinkCellImgEdit EnhancedLinkCellImg_{0}'></td>";

        // normal item: Item
        const string fmtmd      =   "<td class='EnhancedLinkCellItem EnhancedLinkCellItem_{0}'><a class='EnhancedLink EnhancedLink_{0}' href='{1}' target='{2}' title='{3}'>{4}</a>";
        const string fmtmd2     =   "<td><a class='EnhancedLink EnhancedLink_{0}' href='{1}' target='{2}' title='{3}'>{4}</a>";
        const string xfmtmd     =   "<td class='EnhancedLinkCellItem EnhancedLinkCellItem_{0}'></td>";
        const string xfmtmd2    =   "<td></td>";

        // Description
        const string fmt1   =   "<br /><a class='EnhancedLinkDescription EnhancedLinkDescription_{0}'>{1}</a>";

        // separator item
        const string fmtc       =   "<td valign='center' colspan='{2}'><p class='EnhancedLinkTitle EnhancedLinkTitle_{0}'>{1}</p></td></tr><tr>";
        const string fmtd       =   "<td colspan='{0}'><hr /></td></tr><tr>";

        string _UploadDirectory =   string.Empty;
        string UploadDirectory
        {
            get
            {
                if ( _UploadDirectory != string.Empty )
                    return _UploadDirectory;
                string PortalFullPath   =   portalSettings.PortalFullPath;
                if ( !PortalFullPath.EndsWith("/") )
                    PortalFullPath   +=   "/";
                _UploadDirectory        =   PortalFullPath +Settings[EStr.ENHANCEDLINKS_ICONPATH].ToString().Trim();
                if ( !_UploadDirectory.EndsWith("/") )
                    _UploadDirectory    +=   "/";
               return _UploadDirectory;
            }
        }


        #region General Module Implementation

		public override Guid GuidID 
		{
			get
			{
				return new Guid("{96BC3CE0-0409-4ab1-A0C2-67D6C4D68193}");
			}
		}
        #endregion

        #region CTor and Initializer

        public EnhancedLinks()
		{
            if ( ModuleTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]EnhancedLinks Ctor Called.",ModuleTraceSwitch.Sw.Info);
        }
   
        public override string ExtendedResourcesGroup 
		{
            get
            {
                const string extgrp             =   "ENHANCEDLINKS";
                return extgrp;
            }
		}

        public override void InitPortalModuleControl(ModuleSettingsDictionary bSettings)
        {
            PortalModuleInitializer =   new EnhancedLinksSI(bSettings,this);
        }

        #endregion

		/// <summary>
		/// The Page_Load event handler on this User Control is used to
		/// obtain a DataReader of link information from the EnhancedLinks
		/// table, and then databind the results to a templated DataList
		/// server control.  It uses the AddonNice.EnhancedLinkDB()
		/// data component to encapsulate all data functionality.
        /// Html code generated uses following css class
        ///                         EnhancedLinkTitle EnhancedLinkTitle_{0}
        ///                         EnhancedLink EnhancedLink_{0}
        ///                         EnhancedLinkDescription EnhancedLinkDescription_{0}
        ///                         where {0} is Current Module Layout
		/// </summary>
		protected void Page_Load(object sender, System.EventArgs e) 
		{
            if (ModuleTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Enhancedlinks Page_Load BEG isPostBack: {0}", IsPostBack), ModuleTraceSwitch.Sw.Info);
			bool dropDownList		            =   Settings[EStr.ENHANCEDLINKS_SWITCHERTYPES].ToString().Equals("1");
			if (dropDownList)
			{
				if (!Page.IsPostBack) 
				{
					results.Visible			    =   false;
					cboLinks.Visible		    =   true;
					cboLinks.DataSource		    =   mountDataList();
					cboLinks.DataTextField	    =   "TextField";
					cboLinks.DataValueField     =   "ValueField";
					cboLinks.SelectedIndex	    =   0;
					cboLinks.DataBind();
				}
				return;
			}
            BindData();
            if (ModuleTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Enhancedlinks Page_Load END isPostBack: {0}", IsPostBack), ModuleTraceSwitch.Sw.Info);
        }
        
        void BindData()
        {
            if (ModuleTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Enhancedlinks BindData BEG isPostBack: {0}", IsPostBack), ModuleTraceSwitch.Sw.Info);
			string defaultImage		            =   Settings[EStr.ENHANCEDLINKS_DEFAULTIMAGE].ToString();
			bool doExpandAll		            =   Settings[EStr.ENHANCEDLINKS_EXPANDALL].ToBool();
            bool drawHr                         =   Settings[EStr.ENHANCEDLINKS_DRAWHR].ToBool();
			int maxColumns			            =   Settings[EStr.ENHANCEDLINKS_MAXCOLUMS].ToInt();
            if ( maxColumns < 1 )
                maxColumns                      =   1;
			int resize			                =   Settings[EStr.ENHANCEDLINKS_PERCENT_RESIZE_IMG].ToInt();
			int cellpadding			            =   Settings[EStr.ENHANCEDLINKS_CELLPADDING].ToInt();
			int cellspacing			            =   Settings[EStr.ENHANCEDLINKS_CELLSPACING].ToInt();
            
			int actualColumn		            =   1;
			int itemCount					    =   0;
			StringBuilder listStr			    =   new StringBuilder();
			listStr.AppendFormat(fmttbl,cellspacing,cellpadding,CurrentModulesLayout.Name);
			SqlDataReader dr                    =   null;
			try
			{
				dr                              =   eDB.GetEnhancedLinksGlobalized(ModuleID);

				listStr.Append("<tr>");

				while (dr.Read())
				{
					string imageStr             =   (string)dr["ImageUrl"];
					string linkStr		        =   (string)dr["Url"];
					string titleStr		        =   (string)dr["Title"];
					string descStr		        =   (string)dr["Description"];
					string targetStr	        =   (string)dr["Target"];
					bool isSeparator	        =   linkStr.Equals(StStr.SEPARATOR);

                    if ( linkStr.StartsWith(StStr.INTERNAL,false,CultureInfo.InvariantCulture) )
                    {
                        int pgId                =   int.Parse(linkStr.Substring(9));
                        linkStr                 =   HttpUrlBuilder.BuildUrl(pgId);
                        if (ModuleTraceSwitch.Sw.TraceVerbose)
                            Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Enhancedlinks DataBind linkStr: {0}", linkStr), ModuleTraceSwitch.Sw.Info);
                    }
					// when a separator is encountered we must insert an empty row
                    // if separator is first item, this empty row must be sized with normal columns sizing to have correct column size if applicable
                    if (isSeparator )
					{
					    if ( itemCount != 0 )
					    {
                            int colspan             =   (1+maxColumns-actualColumn)*(3+((IsEditable) ? 1:0))-1; // img+link+colsep+ (edit if editable)
                            if (colspan < 1 )
                                colspan             =   1;
						    //listStr.AppendFormat("<td colspan='{0}'>&nbsp;</td></tr><tr>",colspan);
						    listStr.AppendFormat("<td colspan='{0}'>&nbsp;</td>",colspan);
					    }
					    else //  itemCount == 0 : to have correct column spacing we force a first line empty with normal columns sizing
					    {
                            for ( int i = 0 ; i < maxColumns ; i++ )
                            {
					            if (IsEditable)
					            {
						            listStr.Append(xfmta);
					            }
                                if ( maxColumns == 1 )
                                {
                                    if ( IsEditable )
                                            listStr.Append(xfmtbe);
                                    else    listStr.AppendFormat(xfmtb,CurrentModulesLayout.Name);
						            listStr.AppendFormat(xfmtmd,CurrentModulesLayout.Name);
                                }
                                else
                                {
                                    if ( IsEditable )
                                            listStr.Append(xfmtbe);
                                    else    listStr.AppendFormat(xfmtb0,CurrentModulesLayout.Name);
						            listStr.Append(xfmtmd2);
                                }
                                if ( i != (maxColumns-1) )
                                    listStr.Append(fmt2);// separator col
                            }
					    }
					    listStr.Append(fmt4);// </tr><tr>
						actualColumn            =   1;
					}
					if (IsEditable)
					{
						listStr.AppendFormat(fmta,GetLinkUrl(dr["ItemID"].ToString(), linkStr, true));
					}
					string auxImage             =   string.Empty;
					// if some image is specified
                    if (!string.IsNullOrEmpty(imageStr))
					{
                        if ( !imageStr.StartsWith(UploadDirectory) && !imageStr.StartsWith("/") && !imageStr.StartsWith("~/") )
						        auxImage                =   UploadDirectory + imageStr;
						else    auxImage                =   imageStr;
					}
					else if ( !isSeparator ) // if no image and not separator take default
                    {
                        if ( !string.IsNullOrEmpty(defaultImage) )
					    {
						    auxImage            =   UploadDirectory + defaultImage;
                            if ( defaultImage.ToLower() == "navlink.gif" )
                                resize          =   0;
					    }
					    else
					    {
						    auxImage            =   Config.PortalSpecialImagesPath + "/navlink.gif";
                            resize              =   0;
					    }
                    }
                    if ( !string.IsNullOrEmpty(auxImage) ) // could be separator or normal item, for normal item, when title is empty, image is insode the link
                    {
                        if ( resize > 0 )
                        {
                            if ( maxColumns == 1 )
                            {
                                if ( IsEditable )
                                {
                                    if ( !string.IsNullOrEmpty(titleStr) )
                                        listStr.AppendFormat(fmtbe,new object[]{auxImage,titleStr,resize,CurrentModulesLayout.Name});
                                    else    listStr.AppendFormat(fmtbemd2,new object[]{auxImage,titleStr,resize,CurrentModulesLayout.Name,
                                        GetLinkUrl(null, linkStr, false),targetStr,descStr.ToString()});
                                }
                                else
                                {
                                    if ( !string.IsNullOrEmpty(titleStr) )
                                            listStr.AppendFormat(fmtb,new object[]{auxImage,titleStr,resize,CurrentModulesLayout.Name});
                                    else    listStr.AppendFormat(fmtbmd2,new object[]{auxImage,titleStr,resize,CurrentModulesLayout.Name,
                                        GetLinkUrl(null, linkStr, false),targetStr,descStr.ToString()});
                                }
                            }
                            else
                            {
                                if ( IsEditable )
                                {
                                    if ( !string.IsNullOrEmpty(titleStr) )
                                        listStr.AppendFormat(fmtbe0,new object[]{auxImage,titleStr,resize,CurrentModulesLayout.Name});
                                    else    listStr.AppendFormat(fmtbe0md2,new object[]{auxImage,titleStr,resize,CurrentModulesLayout.Name,
                                        GetLinkUrl(null, linkStr, false),targetStr,descStr.ToString()});
                                }
                                else    
                                {
                                    if ( !string.IsNullOrEmpty(titleStr) )
                                        listStr.AppendFormat(fmtb0,new object[]{auxImage,titleStr,resize,CurrentModulesLayout.Name});
                                    else    listStr.AppendFormat(fmtb0md2,new object[]{auxImage,titleStr,resize,CurrentModulesLayout.Name,
                                        GetLinkUrl(null, linkStr, false),targetStr,descStr.ToString()});
                                }
                            }
                        }
                        else                        
                        {
                            if ( maxColumns == 1 )
                            {
                                if ( IsEditable )
                                {
                                    if ( !string.IsNullOrEmpty(titleStr) )
                                        listStr.AppendFormat(fmtb2e,auxImage,titleStr,CurrentModulesLayout.Name);
                                    else    listStr.AppendFormat(fmtb2emd2,new object[]{auxImage,titleStr,CurrentModulesLayout.Name,
                                        GetLinkUrl(null, linkStr, false),targetStr,descStr.ToString()});
                                }
                                else
                                {
                                    if ( !string.IsNullOrEmpty(titleStr) )
                                        listStr.AppendFormat(fmtb2,auxImage,titleStr,CurrentModulesLayout.Name);
                                    else    listStr.AppendFormat(fmtb2md2,new object[]{auxImage,titleStr,CurrentModulesLayout.Name,
                                        GetLinkUrl(null, linkStr, false),targetStr,descStr.ToString()});
                                }
                            }
                            else
                            {
                                if ( IsEditable )
                                {
                                    if ( !string.IsNullOrEmpty(titleStr) )
                                        listStr.AppendFormat(fmtb2e0,auxImage,titleStr,CurrentModulesLayout.Name);
                                    else    listStr.AppendFormat(fmtb2e0md2,new object[]{auxImage,titleStr,CurrentModulesLayout.Name,
                                        GetLinkUrl(null, linkStr, false),targetStr,descStr.ToString()});
                                }
                                else
                                {
                                    if ( !string.IsNullOrEmpty(titleStr) )
                                        listStr.AppendFormat(fmtb20,auxImage,titleStr,CurrentModulesLayout.Name);
                                    else    listStr.AppendFormat(fmtb20md2,new object[]{auxImage,titleStr,CurrentModulesLayout.Name,
                                        GetLinkUrl(null, linkStr, false),targetStr,descStr.ToString()});
                                }
                            }
                        }
                    }
                    if ( !isSeparator )
                    {
                        if ( !string.IsNullOrEmpty(titleStr) ) // when title is empty, image is insode the link
                        {
                            if ( maxColumns == 1 )
						            listStr.AppendFormat(fmtmd,new object[]{CurrentModulesLayout.Name,GetLinkUrl(null, linkStr, false),targetStr,descStr.ToString(),titleStr});
						    else    listStr.AppendFormat(fmtmd2,new object[]{CurrentModulesLayout.Name,GetLinkUrl(null, linkStr, false),targetStr,descStr.ToString(),titleStr});
						    if ((doExpandAll) && !string.IsNullOrEmpty(descStr) )
						    {
							    listStr.AppendFormat(fmt1,CurrentModulesLayout.Name,descStr );
						    }
						    listStr.Append(fmt3); // </td>
                        }
						if (actualColumn < maxColumns)
						{
                            listStr.Append(fmt2);// <td>&nbsp;</td>
							actualColumn++;
						}
						else
						{
							listStr.Append(fmt4);// </tr><tr>
							actualColumn        =   1;
						}
                    }
					else // isSeparator
					{
                        int colspan             =   (1+maxColumns-actualColumn)*(3+((IsEditable) ? 1:0))-(2+((IsEditable) ? 1:0)); // img+link+colsep+ (edit if editable)
                        if ( string.IsNullOrEmpty(auxImage) )
                            colspan             +=  1;
                        if (colspan < 1 )
                            colspan             =   1;
						listStr.AppendFormat(fmtc,CurrentModulesLayout.Name,titleStr,colspan);
                        if ( drawHr )
                        {
                            int fullcolspan     =   maxColumns*(3+((IsEditable) ? 1:0))-1;
						    listStr.AppendFormat(fmtd,fullcolspan);
                        }
						actualColumn            =   1;
					}
					itemCount++;
				}
			}
			catch (Exception ex)
			{
				if (ModuleTraceSwitch.Sw.TraceError)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]Enhancedlinks Page_Load ModuleID: {0}, ex : {1}", ModuleID, ex),ModuleTraceSwitch.Sw.Info);
				throw;
			}
			finally
			{
				if (dr != null)
					dr.Close();
			}
            if ( actualColumn > 1 )
            {
                int colspan             =   ( 1 + maxColumns - actualColumn ) * ( 3 + ( ( IsEditable ) ? 1 : 0 ) ) - 1; // img+link+colsep+ (edit if editable)
                if ( colspan < 1 )
                    colspan = 1;
                listStr.AppendFormat("<td colspan='{0}'>&nbsp;</td></tr>",colspan);
            }
            else
            {
                string rslt             =   listStr.ToString();
                if ( rslt.EndsWith("<tr>") )
                    listStr.Remove(rslt.Length-4,4);
            }
			listStr.Append("</table>\r\n");

			if (itemCount>0) 
			{
				results.Visible         =   true;
				results.Controls.Add(ParseControl(listStr.ToString()));
			}
            if (ModuleTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Enhancedlinks BindData END itemCount: {0}", itemCount), ModuleTraceSwitch.Sw.Info);
		}
 
		private static bool IsNumeric(object value) 
		{ 
			try 
			{ 
				double d = System.Double.Parse(value.ToString(), NumberStyles.Any); 
				return true; 
			} 
			catch (FormatException) 
			{ 
				return false; 
			} 
		}

		private ICollection mountDataList() 
		{
			SqlDataReader dr                =   null;
            DataTable dt                    =   new DataTable();
            try
            {
                dr                          =   eDB.GetEnhancedLinksGlobalized(ModuleID);
                dt.Columns.Add(new DataColumn("TextField", typeof(String)));
                dt.Columns.Add(new DataColumn("ValueField", typeof(String)));
                if (IsEditable)
                {
                    dt.Rows.Add(CreateRow(LocalizeHelper.Localize(EStr.ENHANCEDLINKS_EDITLINK, "Edit Link"),string.Empty, dt));
                }
                else
                {
                    dt.Rows.Add(CreateRow(TitleText,string.Empty, dt));
                }
                while (dr.Read())
                {
                    string linkStr          =   (string)dr["Url"];
                    if (!linkStr.Equals(StStr.SEPARATOR))
                    {
                        dt.Rows.Add(CreateRow((string)dr["Title"], dr["ItemID"].ToString(), dt));
                    }
                }
            }
            catch (Exception ex)
            {
                if (ModuleTraceSwitch.Sw.TraceError)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]Enhancedlinks mountDataList ex : {0}", ex), ModuleTraceSwitch.Sw.Info);
                throw;
            }
            finally
            {
                if (dr != null)
                    dr.Close();
            }
			DataView dv                     =   new DataView(dt);
			return dv;
		}

		private DataRow CreateRow(String Text, String Value, DataTable dt)
		{
			DataRow dr  =   dt.NewRow();
			dr[0]       =   Text;
			dr[1]       =   Value;
			return dr;
		}

		private string GetLinkUrl(object itemID, object url, bool editionMode)
		{
			if (editionMode) 
			{
				if (IsEditable)
				{
					return HttpUrlBuilder.BuildUrl(Config.ModulesPath +"/EnhancedLinks/EnhancedLinksEdit.aspx","ItemID=" + itemID.ToString() + "&mid=" + ModuleID.ToString());
				}
				return string.Empty;
			} 
			else 
			{
				string linkStr      =    url.ToString();
				if ( linkStr.IndexOf("://") < 0 ) 
				{
					if (IsNumeric(linkStr)) 
					{                    
						return HttpUrlBuilder.BuildUrl(int.Parse(linkStr));
					} 
					if ( linkStr.IndexOf("~/") < 0) 
					{
						linkStr     =   "~/" + linkStr;
					}
					return HttpUrlBuilder.BuildUrl(linkStr);
				} 
				return linkStr;
			}
		}

		protected void cmdGo(object sender, System.EventArgs e) 
		{
			string auxItem          =   cboLinks.SelectedItem.Value;
			cboLinks.SelectedIndex  =   0;
			if (IsEditable) 
			{
				Response.Redirect(GetLinkUrl(auxItem, null, true), true);
			} 
			string strURL           =   string.Empty;
			SqlDataReader dr        =   null;
            try
            {
                dr                  =   eDB.GetSingleEnhancedLink(Int32.Parse(auxItem));
                if (dr.Read())
                {
                    strURL          =   dr["Url"].ToString();
                }
            }
            catch (Exception ex)
            {
                if (ModuleTraceSwitch.Sw.TraceError)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]Enhancedlinks cmdGo ModuleID: {0}, ex : {1}", ModuleID, ex), ModuleTraceSwitch.Sw.Info);
                throw;
            }
            finally
            {
                if (dr != null)
                    dr.Close();
            }
            if ( strURL.StartsWith(StStr.INTERNAL,false,CultureInfo.InvariantCulture) )
            {
                int pgId                =   int.Parse(strURL.Substring(9));
                strURL                  =   HttpUrlBuilder.BuildUrl(pgId);
                if (ModuleTraceSwitch.Sw.TraceVerbose)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Enhancedlinks cmdGo strURL: {0}", strURL), ModuleTraceSwitch.Sw.Info);
            }
			Response.Redirect(GetLinkUrl(null, strURL, false), true);
		}

        #region Std overrides
        
        /// <summary>
        /// Triggered from Page.OnPreInit
        /// We must set the Add button before buttons are initialized by base method
        /// </summary>
        public override void Page_PreInit(object sender, EventArgs e)
        {
            AddUrl      =   Config.ModulesPath + "/EnhancedLinks/EnhancedLinksEdit.aspx";
            AddText     =   "ADD";
            base.Page_PreInit(sender, e);
        }
       
		override protected void OnInit(EventArgs e)
        {
            InitializeComponent();
			base.OnInit(e);
        }

		private void InitializeComponent() 
		{
            Load                            +=  new EventHandler(Page_Load);
			cboLinks.SelectedIndexChanged	+=  new EventHandler(cmdGo);
		}
        
		#endregion
	}
}
